<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="SpringBoot创建项目, SongX64">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="baidu-site-verification" content="code-8GV6uhDsco" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>SpringBoot创建项目 | SongX64</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="SongX64" type="application/atom+xml">
</head>



   <style>
    body{
       background-image: url(https://gitee.com/songx86/SongPicBed/raw/master/img/fd039245d688d43f5595595b7d1ed21b0ef43b5f.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">SongX64</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">SongX64</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/1/04.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">SpringBoot创建项目</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/Springboot/">
                                <span class="chip bg-color">Springboot</span>
                            </a>
                        
                            <a href="/tags/%E5%B8%B8%E7%94%A8%E7%BB%84%E4%BB%B6/">
                                <span class="chip bg-color">常用组件</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                后端
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-03-12
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    8.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    35 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="SpringBoot创建项目"><a href="#SpringBoot创建项目" class="headerlink" title="SpringBoot创建项目"></a>SpringBoot创建项目</h1><h2 id="导入"><a href="#导入" class="headerlink" title="导入"></a>导入</h2><p>首先把html放到template文件夹中，可以使用Thymeleaf模板功能。如果放到static文件夹下就不能用。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1568275112273.png" alt="结构图"></p>
<p>同样，dao，entities，controller也是放到相应的文件夹下</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1568275189019.png" alt="1568275189019"></p>
<p>然后我是在HelloController中修改了”&quot;和“\index”的Mapping，修改启动主页：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">"/"</span><span class="token punctuation">,</span><span class="token string">"zuye"</span><span class="token punctuation">,</span><span class="token string">"index"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token class-name">ZuYe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token string">"login"</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li><strong>500错误</strong>：未在pom.xml引入spring-boot-starter-thymeleaf启动器依赖</li>
</ul>
<h1 id="SpringBoot配置文件"><a href="#SpringBoot配置文件" class="headerlink" title="SpringBoot配置文件"></a>SpringBoot配置文件</h1><p>首先在<strong>pom.xml</strong>中引入<strong>配置文件解释器</strong>：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--配置文件处理器--></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>spring-boot-configuration-processor<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>optional</span><span class="token punctuation">></span></span>true<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>optional</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>引入了之后就会有提示了。</p>
<h2 id="application文件举例"><a href="#application文件举例" class="headerlink" title="application文件举例"></a>application文件举例</h2><p>配置文件默认是<strong>application.properties或者是application.yml</strong></p>
<p>举例：</p>
<h3 id="application-properties"><a href="#application-properties" class="headerlink" title="application.properties"></a>application.properties</h3><pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token comment">#配置person的值，与yml语法不一样</span>
<span class="token comment">#引入配置文件处理器后，可以自动提示</span>
<span class="token attr-name">person.last-name</span><span class="token punctuation">=</span> <span class="token attr-value">张三</span>
<span class="token attr-name">person.age</span><span class="token punctuation">=</span><span class="token attr-value">19</span>
<span class="token attr-name">person.birth</span><span class="token punctuation">=</span><span class="token attr-value">2001/03/04</span>
<span class="token attr-name">person.boss</span><span class="token punctuation">=</span><span class="token attr-value">false</span>
<span class="token attr-name">person.list</span><span class="token punctuation">=</span><span class="token attr-value">a,b,c</span>
<span class="token attr-name">person.maps.k1</span><span class="token punctuation">=</span><span class="token attr-value">v1</span>
<span class="token attr-name">person.maps.k2</span><span class="token punctuation">=</span><span class="token attr-value">12</span>
<span class="token attr-name">person.dog.name</span><span class="token punctuation">=</span><span class="token attr-value">dog</span>
<span class="token attr-name">person.dog.age</span><span class="token punctuation">=</span><span class="token attr-value">2</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="application-yml"><a href="#application-yml" class="headerlink" title="application.yml"></a>application.yml</h3><pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">server:
  port: 8081

person:
  lastName: zhang
  age: 18
  boss: false
  birth: 2001&#x2F;12&#x2F;12

  #数组、list、set
  list:
    - lisi
    - wangwu
  #数组行内写法
  list: [lisi,wangwu]
  #对象或Map，k-v
  dog:
    name: Tom
    age: 3
  #对象或Map行内写法
  maps: &#123;k1: v1, k2: 12&#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li><p>yml一定要在 “冒号：” 后面加个<strong>空格</strong>，不然识别不了。</p>
</li>
<li><p>yml是<em><strong>缩进控制</strong></em>的语法，大小写敏感。</p>
</li>
<li><p>占位符，yml和properties都支持</p>
</li>
</ul>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">#随机uid
person.last-name&#x3D;张三$&#123;random.uuid&#125;
#随机int
person.age&#x3D;$&#123;random.int&#125;
#指定属性值
#这样出来就是“张三uid_cat”
person.cat.name&#x3D;$&#123;person.name&#125;_cat
#没有hello属性，会使用冒号后面的默认值；如果不加默认值的话，会直接输出这个式子
person.dog.name&#x3D;$&#123;person.hello:hello&#125;_dog<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Profile"><a href="#Profile" class="headerlink" title="Profile"></a>Profile</h2><p>SpringBoot支持配置文件多Profile，形式如application-dev.yml(开发环境配置文件),application-pro.properties(生产环境配置文件)。</p>
<p>这样命名之后可以直接通过一些方式来指定使用哪一个配置文件。</p>
<p>这里的名字是可以随便起的（符合规范别xjb起就行）。</p>
<h3 id="yml多文档块方式"><a href="#yml多文档块方式" class="headerlink" title="yml多文档块方式"></a>yml多文档块方式</h3><pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">#我们假设不同环境使用的端口不同
#文档块1，prod环境，active表明现在是激活的
server: 
	port: 8081
spring: 
	profiles: 
		active: prod

---
#3个横线分割文档块，下面就相当于第2个文档了
#spring.profiles,就是指定是啥profiles环境了
server:
	port: 8082
spring: 
	profiles: dev

---
#第3个也一样
server: 
	port: 8083
spring: 
	profiles: prod<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="指定profile"><a href="#指定profile" class="headerlink" title="指定profile"></a>指定profile</h3><ol>
<li><p>配置文件中直接写，比如上面的<code>spring.profiles.active=prod</code></p>
</li>
<li><p>命令行中指定参数：<br>在项目打jar包之后，使用命令行进行部署时可以像这个命令一样指定profiles：<br><code>java -jar jar包名.jar -spring.profiles.active=dev ;</code><br>或者可以在IDEA中运行设置，Edit Configuation中的Program arguments填写<code>spring.profiles.active=dev</code></p>
</li>
<li><p>虚拟机参数:<br>在Edit Configuations中的VM options:：</p>
<p>-Dspring.profiles.active=dev</p>
<!--这里的 -D是必须的，指定虚拟机参数-->

<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1567735965139.png" alt="Edit Configurations"></p>
</li>
</ol>
<h3 id="配置文件加载位置"><a href="#配置文件加载位置" class="headerlink" title="配置文件加载位置"></a>配置文件加载位置</h3><ul>
<li><p>4个位置：</p>
<p>优先级从高到低，属性不同互补，相同高的覆盖低的</p>
<p>-file: /config/                当前文件夹下的config文件夹下（比如整个项目文件夹下）<br>-file: /                            文件夹下根目录里<br>-classpath: /config/    类目录下的config文件夹下（IDEA里面的<br>-classpath: /                类目录下的根目录里<br><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1567736810626.png" alt="1567736810626"></p>
</li>
<li><p>指定配置文件路径</p>
<p>在默认的全局配置文件中可以写:</p>
<p><code>spring.config.loactions=G:/application.properties</code></p>
</li>
</ul>
<h3 id="配置文件加载优先级"><a href="#配置文件加载优先级" class="headerlink" title="配置文件加载优先级"></a>配置文件加载优先级</h3><p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html">这里具体参见官方文档</a></p>
<p>我们重点关注以下几个顺序，优先级都是从高到低的：</p>
<ol>
<li><p>命令行参数</p>
<p><strong>jar包外向jar包内进行寻找</strong></p>
<p><strong>优先加载带profile的</strong></p>
</li>
<li><p>jar包外的application-{profiles}配置文件(properties或yml)</p>
</li>
<li><p>jar包内的application-{profiles}配置文件</p>
<p><strong>之后是不带profile的</strong></p>
</li>
<li><p>jar包外的application.properties或yml</p>
</li>
<li><p>jar包内的application.properties或yml</p>
</li>
<li><p>@Configuration注解类上的@PropertySource</p>
</li>
</ol>
<h1 id="自动配置的原理"><a href="#自动配置的原理" class="headerlink" title="自动配置的原理"></a>自动配置的原理</h1><p>这里涉及到比较底层的Spring注解，先暂时跳过了。</p>
<h1 id="SpringBoot日志"><a href="#SpringBoot日志" class="headerlink" title="SpringBoot日志"></a>SpringBoot日志</h1><p>日志分为日志门面（日志的抽象层）和日志实现</p>
<p>SpringBoot：底层是Spring框架，Spring框架默认使用JCL（很久没有更新过了）</p>
<p>​    <strong>SpringBoot选用的是SLF4（门面）和logback（实现）</strong></p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//记录器</span>
<span class="token class-name">Logger</span> logger <span class="token operator">=</span> <span class="token class-name">LoggerFactory</span><span class="token punctuation">.</span><span class="token function">getLogger</span><span class="token punctuation">(</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">contextLoads</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token comment">//System.out.println();</span>

	<span class="token comment">//日志的级别；</span>
	<span class="token comment">//由低到高   trace&lt;debug&lt;info&lt;warn&lt;error</span>
	<span class="token comment">//可以调整输出的日志级别；日志就只会在这个级别以以后的高级别生效</span>
	logger<span class="token punctuation">.</span><span class="token function">trace</span><span class="token punctuation">(</span><span class="token string">"这是trace日志..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	logger<span class="token punctuation">.</span><span class="token function">debug</span><span class="token punctuation">(</span><span class="token string">"这是debug日志..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token comment">//SpringBoot默认给我们使用的是info级别的，没有指定级别的就用SpringBoot默认规定的级别；root级别</span>
	logger<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"这是info日志..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	logger<span class="token punctuation">.</span><span class="token function">warn</span><span class="token punctuation">(</span><span class="token string">"这是warn日志..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	logger<span class="token punctuation">.</span><span class="token function">error</span><span class="token punctuation">(</span><span class="token string">"这是error日志..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<pre class="line-numbers language-none"><code class="language-none">  日志输出格式：
%d表示日期时间，
%thread表示线程名，
%-5level：级别从左显示5个字符宽度
%logger&#123;50&#125; 表示logger名字最长50个字符，否则按照句点分割。 
%msg：日志消息，
%n是换行符
  --&gt;
  %d&#123;yyyy-MM-dd HH:mm:ss.SSS&#125; [%thread] %-5level %logger&#123;50&#125; - %msg%n<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>SpringBoot修改日志的默认配置</p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token attr-name">logging.level.com.atguigu</span><span class="token punctuation">=</span><span class="token attr-value">trace</span>


<span class="token comment">#logging.path=</span>
<span class="token comment"># 不指定路径在当前项目下生成springboot.log日志</span>
<span class="token comment"># 可以指定完整的路径；</span>
<span class="token comment">#logging.file=G:/springboot.log</span>

<span class="token comment"># 在当前磁盘的根路径下创建spring文件夹和里面的log文件夹；使用 spring.log 作为默认文件</span>
<span class="token attr-name">logging.path</span><span class="token punctuation">=</span><span class="token attr-value">/spring/log</span>

<span class="token comment">#  在控制台输出的日志的格式</span>
<span class="token attr-name">logging.pattern.console</span><span class="token punctuation">=</span><span class="token attr-value">%d&#123;yyyy-MM-dd&#125; [%thread] %-5level %logger&#123;50&#125; - %msg%n</span>
<span class="token comment"># 指定文件中日志输出的格式</span>
<span class="token attr-name">logging.pattern.file</span><span class="token punctuation">=</span><span class="token attr-value">%d&#123;yyyy-MM-dd&#125; === [%thread] === %-5level === %logger&#123;50&#125; ==== %msg%n</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<table>
<thead>
<tr>
<th>logging.file</th>
<th>logging.path</th>
<th>Example</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>(none)</td>
<td>(none)</td>
<td></td>
<td>只在控制台输出</td>
</tr>
<tr>
<td>指定文件名</td>
<td>(none)</td>
<td>my.log</td>
<td>输出日志到my.log文件</td>
</tr>
<tr>
<td>(none)</td>
<td>指定目录</td>
<td>/var/log</td>
<td>输出到指定目录的 spring.log 文件中</td>
</tr>
</tbody></table>
<h1 id="整合JDBC"><a href="#整合JDBC" class="headerlink" title="整合JDBC"></a>整合JDBC</h1><ol>
<li>添加pom依赖</li>
<li>配置文件中添加数据库驱动，用户名，密码，url</li>
<li>新建DataSource对象getConnection()一下，来看看是否连接成功</li>
</ol>
<p>新建项目时勾选MySQL和JDBC:</p>
<h2 id="pom-xml中jdbc和mysql的依赖"><a href="#pom-xml中jdbc和mysql的依赖" class="headerlink" title="pom.xml中jdbc和mysql的依赖"></a>pom.xml中jdbc和mysql的依赖</h2><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>spring-boot-starter-data-jdbc<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>


<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>mysql<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>mysql-connector-java<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>scope</span><span class="token punctuation">></span></span>runtime<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>scope</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="配置文件"><a href="#配置文件" class="headerlink" title="配置文件"></a>配置文件</h2><p>然后在配置文件中，增加数据库连接的属性：</p>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">spring:
  datasource:
    #   数据源基本配置
    initialization-mode: always
    username: root
    password: 123456
    url: jdbc:mysql:&#x2F;&#x2F;localhost:3306&#x2F;springbootlearn?serverTimezone&#x3D;UTC
    driver-class-name: com.mysql.cj.jdbc.Driver<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>遇到问题：</p>
<p>抛出<code>The server time zone value &#39;�й���׼ʱ��&#39; is unrecogni</code>错误 </p>
<p>原因是因为使用了Mysql Connector/J 6.x以上的版本，然后就报了时区的错误</p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties">将原来的连接：
<span class="token attr-name">spring.datasource.url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql://127.0.0.1:3306/</span>
修改为：
<span class="token attr-name">spring.datasource.url</span><span class="token punctuation">=</span><span class="token attr-value">jdbc:mysql://localhost:3306/springbootlearn?serverTimezone=UTC</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>添加?serverTimezone=UTC即可解决。</p>
<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><p>SpringBoot测试类：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RunWith</span><span class="token punctuation">(</span><span class="token class-name">SpringRunner</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@SpringBootTest</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SpringBoot06DataJdbcApplicationTests</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token class-name">DataSource</span> dataSource<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Test</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">contextLoads</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">SQLException</span> <span class="token punctuation">&#123;</span>
<span class="token comment">//        输出class com.zaxxer.hikari.HikariDataSource</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>dataSource<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token class-name">Connection</span> connection <span class="token operator">=</span> dataSource<span class="token punctuation">.</span><span class="token function">getConnection</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//        输出HikariProxyConnection@507944445 wrapping com.mysql.cj.jdbc.ConnectionImpl@554f0dfb</span>
<span class="token comment">//        说明SpringBoot2.0+使用的默认数据源是:com.zaxxer.hikari.HikariDataSource</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>connection<span class="token punctuation">)</span><span class="token punctuation">;</span>
        connection<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h1 id="使用阿里数据源Druid"><a href="#使用阿里数据源Druid" class="headerlink" title="使用阿里数据源Druid"></a>使用阿里数据源Druid</h1><ol>
<li><p>添加依赖</p>
</li>
<li><p>在配置文件中增加属性，特别是type修改使用数据源</p>
</li>
<li><p>编写配置类</p>
</li>
</ol>
<p>​    数据源是一种提高数据库连接性能的常规手段，它会创建一个数据连接池，由它来管理数据库连接，而不需要手动的频繁打开或关闭数据库连接从而提高了性能。</p>
<p>​    DRUID是阿里巴巴开源平台上一个数据库连接池实现，它结合了C3P0、DBCP、PROXOOL等DB池的优点，同时加入了<strong>日志监控</strong>，可以很好的监控DB池连接和SQL的执行情况，可以说是针对监控而生的DB连接池，据说是目前最好的连接池。</p>
<p>​    上面SpringBoot默认的数据源是com.zaxxer.hikari.HikariDataSource，然后我们将其修改为alibaba的Druid。</p>
<p>在上面的基础上进行修改：</p>
<h2 id="pom-xml引入依赖"><a href="#pom-xml引入依赖" class="headerlink" title="pom.xml引入依赖"></a>pom.xml引入依赖</h2><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!-- https://mvnrepository.com/artifact/com.alibaba/druid --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>com.alibaba<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>druid<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>1.1.8<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    具体依赖还有各种版本可以去Maven Repository网站搜Druid</p>
<h2 id="修改配置文件"><a href="#修改配置文件" class="headerlink" title="修改配置文件"></a>修改配置文件</h2><pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">spring:
  datasource:
    #   数据源基本配置
    initialization-mode: always
    username: root
    password: 123456
    url: jdbc:mysql:&#x2F;&#x2F;localhost:3306&#x2F;springbootlearn?serverTimezone&#x3D;UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
#    schema:
#      - classpath:department.sql
    type: com.alibaba.druid.pool.DruidDataSource

    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
   
   #   配置监控统计拦截的filters，去掉后监控界面sql无法统计，&#39;wall&#39;用于防火墙
   #   监控统计用的filter:stat；日志用的filter:log4j；防御sql注入的filter:wall
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql&#x3D;true;druid.stat.slowSqlMillis&#x3D;500
    # 配置多久进行一次检测，检测需要关闭的空闲连接 单位毫秒
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    主要是修改type，改变数据源。然后进行其他具体参数设置。</p>
<h2 id="编写配置类DruidConfig"><a href="#编写配置类DruidConfig" class="headerlink" title="编写配置类DruidConfig"></a>编写配置类DruidConfig</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DruidConfig</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@ConfigurationProperties</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"spring.datasource"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">DataSource</span> <span class="token function">druid</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">DruidDataSource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//配置Druid的监控</span>

    <span class="token comment">//1.配置一个管理后后台的servlet,这个Bean加到容器中</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">ServletRegistrationBean</span> <span class="token function">statViewServlet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ServletRegistrationBean</span> bean <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ServletRegistrationBean</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StatViewServlet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"/druid/*"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token comment">//配置初始化参数，因为下面需要传入一个map</span>
        <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> initParams <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//这个东西的参数去StatViewServlet类里面，他的父类ResourceServlet里面找</span>
        initParams<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"loginUsername"</span><span class="token punctuation">,</span> <span class="token string">"admin"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        initParams<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"loginPassword"</span><span class="token punctuation">,</span> <span class="token string">"123456"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//        initParams.put("allow", "");    //允许谁访问，默认是所有</span>
<span class="token comment">//        initParams.put("deny","192.168.15.21"); //拒绝谁放问，这里是假设的IP地址</span>
        <span class="token comment">//需要传入一个map</span>
        bean<span class="token punctuation">.</span><span class="token function">setInitParameters</span><span class="token punctuation">(</span>initParams<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> bean<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token comment">//    2.配置一个web监控的filter</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">FilterRegistrationBean</span> <span class="token function">webStatFilter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">FilterRegistrationBean</span> bean <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FilterRegistrationBean</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        bean<span class="token punctuation">.</span><span class="token function">setFilter</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">WebStatFilter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> initParams <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//同理去看WebStatFilter里面。这个是排除的不拦截的请求</span>
        initParams<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"exclusions"</span><span class="token punctuation">,</span> <span class="token string">"*.js,*.css,/druid/*,/druid"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        bean<span class="token punctuation">.</span><span class="token function">setInitParameters</span><span class="token punctuation">(</span>initParams<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//要拦截哪些请求,需要一个collection参数。拦截所有请求</span>
        bean<span class="token punctuation">.</span><span class="token function">setUrlPatterns</span><span class="token punctuation">(</span><span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">"/*"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> bean<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    总的来说，就是写了一个Servlet和一个Filter注入到容器中。</p>
<p>​    <strong>Servlet是用来处理请求，显示Druid的界面；</strong></p>
<p>​    <strong>Filter是拦截网页的请求（部分静态资源除外），用来统计监控数据。</strong></p>
<p>​    servlet是用于显示druid管理界面，并对其中的一些参数进行设置；</p>
<p>​    filter是对请求进行拦截，通过拦截对数据进行统计。</p>
<p>​    编写完配置类之后，要在主程序入口Application上面添加@ServletComponentScan注解扫描所有的Servlet。</p>
<h2 id="访问页面"><a href="#访问页面" class="headerlink" title="访问页面"></a>访问页面</h2><p>访问上面设置的servlet地址即可,<code>localhost:8080/druid</code>,会自动跳转到登录页面，其中的账号密码就是上面设置的参数中的loginUsername和loginPassword。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1569746128404.png" alt="Druid界面"></p>
<blockquote>
<p>PS：使用druid要添加log4j日志依赖，因为druid用到了这玩意，不加会报错</p>
</blockquote>
<h1 id="整合MyBatis"><a href="#整合MyBatis" class="headerlink" title="整合MyBatis"></a>整合MyBatis</h1><p>整合MyBatis依然在上面的基础上进行。</p>
<p>有两种方式：</p>
<pre><code>1. 注解方式
2. xml配置文件方式
</code></pre>
<p>自我感觉整合MyBatis的核心就是写Mapper</p>
<p>何为ORM框架/Hibernate/…</p>
<p>先做杂项工作：编写两个POJO普通类，同时数据库中建两个相应的表。</p>
<h2 id="注解版"><a href="#注解版" class="headerlink" title="注解版"></a>注解版</h2><h3 id="编写Mapper"><a href="#编写Mapper" class="headerlink" title="编写Mapper"></a>编写Mapper</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//指定这是一个操作数据库的mapper</span>
<span class="token annotation punctuation">@Mapper</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">DepartmentMapper</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Select</span><span class="token punctuation">(</span><span class="token string">"select * from department"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Department</span><span class="token punctuation">></span></span> <span class="token function">getDeptAll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">//这些注解都是mybatis里面规定的注解</span>
    <span class="token annotation punctuation">@Select</span><span class="token punctuation">(</span><span class="token string">"select * from department where id=#&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">getDeptById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Delete</span><span class="token punctuation">(</span><span class="token string">"delete from department where id=#&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">deleteDeptByID</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">//表中的id是自增的，所以说只插入name就行了</span>
    <span class="token comment">//Options告诉Mapper我们使用了自动创建的键，键的名字是id，这时候这个注解就会自动把id在封装到返回的department里面</span>
    <span class="token annotation punctuation">@Options</span><span class="token punctuation">(</span>useGeneratedKeys <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">,</span>keyProperty <span class="token operator">=</span> <span class="token string">"id"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@Insert</span><span class="token punctuation">(</span><span class="token string">"insert into department(departmentName) values(#&#123;departmentName&#125;)"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">insertDept</span><span class="token punctuation">(</span><span class="token class-name">Department</span> department<span class="token punctuation">)</span><span class="token punctuation">;</span>


    <span class="token comment">//根据id来更新信息</span>
    <span class="token annotation punctuation">@Update</span><span class="token punctuation">(</span><span class="token string">"update department set departmentName=#&#123;departmentName&#125; where id=#&#123;      id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">updateDept</span><span class="token punctuation">(</span><span class="token class-name">Department</span> department<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>关于<strong>注解中的值和参数的关系</strong>，比如#{id}，对应的是下面参数中<strong>同名的参数</strong>(比如上面的Integer id)；或者是下面参数是对象，对象中的同名的属性值：</p>
<blockquote>
<h4 id="使用对象"><a href="#使用对象" class="headerlink" title="使用对象"></a>使用对象</h4><p>如果我们使用普通的java对象作为查询条件的参数：</p>
<pre class="line-numbers language-none"><code class="language-none">@Insert(&quot;INSERT INTO T_USER(NAME, PASSWORD, PHONE) VALUES(#&#123;name&#125;, #&#123;password&#125;, #&#123;phone&#125;)&quot;)
int insertByUser(User user);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>


<p>只需要语句中的#{name}、#{age}就分别对应了User对象中的name和age属性。</p>
<pre class="line-numbers language-none"><code class="language-none">User u &#x3D; new User();
	u.setName(&quot;赵六&quot;);
	u.setPassword(&quot;12312312&quot;);
	u.setPhone(&quot;13888888888&quot;);
	userMapper.insertByUser(u);<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</blockquote>
<pre><code>@Insert(&quot;INSERT INTO T_USER(NAME, PASSWORD, PHONE) VALUES(#&#123;name&#125;, #&#123;password&#125;, #&#123;phone&#125;)&quot;)
int insertByUser(User user);
只需要语句中的#&#123;name&#125;、#&#123;age&#125;就分别对应了User对象中的name和age属性。
User u = new User();
    u.setName(&quot;赵六&quot;);
    u.setPassword(&quot;12312312&quot;);
    u.setPhone(&quot;13888888888&quot;);
    userMapper.insertByUser(u);
</code></pre>
<p>关于这里的传参方式还有几种，比如@Param注解、使用Map、还有上面的使用对象。具体参见<a target="_blank" rel="noopener" href="https://blog.csdn.net/winter_chen001/article/details/78623700">这个CSDN博客</a>。</p>
<p>编写Mapper：</p>
<ol>
<li>使用@Mapper注解来说明这是个Mybatis的Mapper映射，然后写成接口？</li>
<li>自定义方法，名字随意，方法参数和注解相对应（如上传参方式）</li>
<li>注解@Insert,@Select等等，在这种注解中写相应的SQL语句（参数如上）。</li>
</ol>
<h3 id="编写Controller"><a href="#编写Controller" class="headerlink" title="编写Controller"></a>编写Controller</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DeptController</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token class-name">DepartmentMapper</span> departmentMapper<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/dept/all"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Department</span><span class="token punctuation">></span></span> <span class="token function">getDeptAll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Department</span><span class="token punctuation">></span></span> list <span class="token operator">=</span>  departmentMapper<span class="token punctuation">.</span><span class="token function">getDeptAll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">//System.out.println(list.toString());</span>
        <span class="token keyword">return</span> list<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//在参数中加上id传过来，然后去查询这个id</span>
    <span class="token comment">//localhost:8080/dept/select/1</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/dept/select/&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">getDepartment</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span> <span class="token class-name">Integer</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> departmentMapper<span class="token punctuation">.</span><span class="token function">getDeptById</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//插入department,带参数?departmentName = xxx</span>
    <span class="token comment">//比如：localhost:8080/dept/insert?departmentName=腾讯</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/dept/insert"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">insertDept</span><span class="token punctuation">(</span><span class="token class-name">Department</span> department<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        departmentMapper<span class="token punctuation">.</span><span class="token function">insertDept</span><span class="token punctuation">(</span>department<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> department<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//删除</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/dept/delete/&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">Department</span> <span class="token function">deleteDeptbyId</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span> <span class="token class-name">Integer</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">Department</span> deleteDept <span class="token operator">=</span> <span class="token function">getDepartment</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        departmentMapper<span class="token punctuation">.</span><span class="token function">deleteDeptByID</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> deleteDept<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>编写Controller来进行测试，调用Mapper中的方法，进行增删改查。注意这里用URL传参的方式。</p>
<h2 id="XML配置文件版"><a href="#XML配置文件版" class="headerlink" title="XML配置文件版"></a>XML配置文件版</h2><h3 id="编写Mapper接口"><a href="#编写Mapper接口" class="headerlink" title="编写Mapper接口"></a>编写Mapper接口</h3><p>这里的Mapper类不需要写注解，只是包含相应的自定义方法，还有方法的参数。其他的相关东西都在xml里。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//需要用@Mapper或者@MapperScan将接口扫描装配到容器中</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">EmployeeMapper</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token class-name">Employee</span> <span class="token function">getEmpById</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> id<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">insertEmp</span><span class="token punctuation">(</span><span class="token class-name">Employee</span> employee<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="编写mybatis-config-xml"><a href="#编写mybatis-config-xml" class="headerlink" title="编写mybatis-config.xml"></a>编写mybatis-config.xml</h3><p>在里面进行各种配置。</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8" ?></span>
<span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">configuration</span>
        <span class="token name">PUBLIC</span> <span class="token string">"-//mybatis.org//DTD Config 3.0//EN"</span>
        <span class="token string">"http://mybatis.org/dtd/mybatis-3-config.dtd"</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>configuration</span><span class="token punctuation">></span></span>
    <span class="token comment">&lt;!--驼峰命名法，解决d_id和dId的问题--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>settings</span><span class="token punctuation">></span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>setting</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>mapUnderscoreToCamelCase<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">/></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>settings</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>configuration</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    这里主要是解决了d_id和dId不同的问题，如果不加这个配置，那么在数据库中的d_id和类中的dId不会匹配。</p>
<h3 id="编写Mapper-xml"><a href="#编写Mapper-xml" class="headerlink" title="编写Mapper.xml"></a>编写Mapper.xml</h3><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8" ?></span>
<span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">mapper</span>
        <span class="token name">PUBLIC</span> <span class="token string">"-//mybatis.org//DTD Mapper 3.0//EN"</span>
        <span class="token string">"http://mybatis.org/dtd/mybatis-3-mapper.dtd"</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--这里的namespace和接口的类名要对应，进行绑定--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>mapper</span> <span class="token attr-name">namespace</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.song.springboot.mapper.EmployeeMapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--  public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);--></span>
    <span class="token comment">&lt;!--这两个方法，用标签的形式在这绑定--></span>
    <span class="token comment">&lt;!--id是方法名，resultType是返回值--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>select</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getEmpById<span class="token punctuation">"</span></span> <span class="token attr-name">resultType</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.song.springboot.bean.Employee<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        SELECT * FROM employee WHERE  id=#&#123;id&#125;
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>select</span><span class="token punctuation">></span></span>
    <span class="token comment">&lt;!--插入，不需要返回值；然后注意这个d_id->dId这个大小写转换--></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>insert</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>insertEmp<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#&#123;lastName&#125;,#&#123;email&#125;,#&#123;gender&#125;,#&#123;dId&#125;)
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>insert</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>mapper</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>注意的地方：</p>
<ul>
<li>namespace：Mapper类名具体的路径</li>
<li>id：应该是和方法名相对应</li>
<li>resultType：返回值类型，也是具体的类路径；返回值为空就不用写</li>
<li>在相应的比如<code>&lt;select&gt;&lt;/select&gt;</code>编写SQL语句即可，值和参数仍然和上面的一样。</li>
</ul>
<h3 id="修改application-yml配置文件"><a href="#修改application-yml配置文件" class="headerlink" title="修改application.yml配置文件"></a>修改application.yml配置文件</h3><pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">#mybatis配置xml方式，xml所在路径
mybatis:
  config-location: classpath:mybatis&#x2F;mybatis-config.xml
  mapper-locations: classpath:mybatis&#x2F;mapper&#x2F;*.xml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>在配置文件中加如上属性，指定mybatis的xml配置文件所在路径。</p>
<h1 id="整合JPA"><a href="#整合JPA" class="headerlink" title="整合JPA"></a>整合JPA</h1><p>整合JPA时也可将数据源换为Druid，但是这里就没再换。</p>
<h2 id="何为JPA"><a href="#何为JPA" class="headerlink" title="何为JPA"></a>何为JPA</h2><p>JPA是Java持久化API，定义了一系列对象持久化的标准，而hibernate是当前非常流行的对象持久化开源框架，Spring boot就<strong>默认集成了</strong>这种框架，加速web应用开发。</p>
<p><strong>spring-boot-starter-data-jpa的启动器中继承了Hibernate</strong>。</p>
<p>这里我们用的<strong>Spring Data JPA</strong>是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,是基于Hibernate之上构建的JPA使用解决方案。</p>
<p>JPA == Java Persistence API（Java 持久层 API）：用于对象持久化的 API</p>
<p>作用：使得应用程序以统一的方式访问持久层</p>
<p>JPA 是 Hibernate 的一个抽象，就像 JDBC 和 JDBC 驱动的关系。JPA是一种规范，而Hibernate是JPA的一个实现。</p>
<p>参考：</p>
<ul>
<li><p><a target="_blank" rel="noopener" href="https://my.oschina.net/u/3080373/blog/1828589">JPA、Hibernate、Spring data jpa之间的关系</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/crawl/p/7703679.html">JPA + SpringData 操作数据库原来可以这么简单 —- 深入了解 JPA - 1</a></p>
</li>
</ul>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1569675646418.png" alt="JPA与ORM"></p>
<p><img src="https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=4eeb27c108087bf469e15fbb93ba3c49/8435e5dde71190ef25b88a55c41b9d16fcfa60fc.jpg" alt="img"></p>
<h2 id="整合JPA-1"><a href="#整合JPA-1" class="headerlink" title="整合JPA"></a>整合JPA</h2><h3 id="pom-xml依赖"><a href="#pom-xml依赖" class="headerlink" title="pom.xml依赖"></a>pom.xml依赖</h3><pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>spring-boot-starter-data-jdbc<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!-- Spring Data的 Jpa starter --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>spring-boot-starter-data-jpa<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>mysql<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>mysql-connector-java<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>scope</span><span class="token punctuation">></span></span>runtime<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>scope</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>PS：spring-boot-starter-data-jpa包括了Hibernate。</p>
<h3 id="application-yml配置文件"><a href="#application-yml配置文件" class="headerlink" title="application.yml配置文件"></a>application.yml配置文件</h3><pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">spring:
  datasource:
    url: jdbc:mysql:&#x2F;&#x2F;localhost:3306&#x2F;jpa?serverTimezone&#x3D;UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
#      自动更新或者创建数据表
      ddl-auto: update
#      控制台显示SQL
    show-sql: true
#    bean的声明可以被覆盖？应该是用于我们自定义的Repository接口注入
  main:
    allow-bean-definition-overriding: true<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>前面DataSource的配置和以前一样，url用户名密码驱动等。</p>
<p>下面的overriding如果不写的话启动不了，根据控制台建议写上的。</p>
<h3 id="实体类"><a href="#实体类" class="headerlink" title="实体类"></a>实体类</h3><p>重点在实体类的注解上：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//使用JPA注解配置映射关系</span>
<span class="token annotation punctuation">@Entity</span>     <span class="token comment">//告诉JPA这是个实体类</span>
<span class="token annotation punctuation">@Table</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"tbl_user"</span><span class="token punctuation">)</span>   <span class="token comment">//告诉这个类和数据库中的哪个表相对应，不写的话就是默认的小写类名user</span>
<span class="token annotation punctuation">@JsonIgnoreProperties</span><span class="token punctuation">(</span>value<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token string">"hibernateLazyInitializer"</span><span class="token punctuation">,</span><span class="token string">"handler"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">User</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Id</span> <span class="token comment">//说明这是主键</span>
    <span class="token annotation punctuation">@GeneratedValue</span><span class="token punctuation">(</span>strategy <span class="token operator">=</span> <span class="token class-name">GenerationType</span><span class="token punctuation">.</span>IDENTITY<span class="token punctuation">)</span> <span class="token comment">//自增主键</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> id<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Column</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"last_name"</span><span class="token punctuation">,</span>length <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">)</span> <span class="token comment">//指定列名</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> lastName<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@Column</span> <span class="token comment">//默认就是列名和属性名一样，emali</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> email<span class="token punctuation">;</span>

    <span class="token comment">//Getter and Setter</span>
    <span class="token keyword">public</span> <span class="token class-name">Integer</span> <span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>@Entiy：说明这是一个POJO类</li>
<li>＠Table：指明这个类和数据库中哪张表映射</li>
<li>@Id：表示这个属性在表中是主键</li>
<li>＠GeneratedVlue：说明了主键的生成方式</li>
<li>@Column：指定这个属性和表中哪个字段对应</li>
</ul>
<h3 id="继承JpaRepository接口"><a href="#继承JpaRepository接口" class="headerlink" title="继承JpaRepository接口"></a>继承JpaRepository接口</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//JpaRepository后面的泛型：要操作的实体类，以及主键的类型</span>
<span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">UserRepository</span> <span class="token keyword">extends</span> <span class="token class-name">JpaRepository</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">,</span> <span class="token class-name">Integer</span><span class="token punctuation">></span></span> <span class="token punctuation">&#123;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>



<h3 id="Controller-调用"><a href="#Controller-调用" class="headerlink" title="Controller 调用"></a>Controller 调用</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">UserController</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@Autowired</span>
    <span class="token class-name">UserRepository</span> userRepository<span class="token punctuation">;</span>


    <span class="token comment">//查找全部</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/user/jpa/all"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">></span></span> <span class="token function">getAllUser</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> userRepository<span class="token punctuation">.</span><span class="token function">findAll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">//查找用户</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/user/jpa/select/&#123;id&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">User</span> <span class="token function">getUser</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span> <span class="token class-name">Integer</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">User</span> user <span class="token operator">=</span> userRepository<span class="token punctuation">.</span><span class="token function">getOne</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> user<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token comment">//插入用户,参数方式</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/user"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">User</span> <span class="token function">insertUser</span><span class="token punctuation">(</span><span class="token class-name">User</span> user<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">User</span> saveUser <span class="token operator">=</span> userRepository<span class="token punctuation">.</span><span class="token function">save</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> saveUser<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里调用的话就直接自动注入一个Repository，然后用它来调用相应的方法如findAll()、getOne()等等即可（Hibernate会自动生成数据库语句，不用手动写）。</p>
<p>在请求的同时，因为在application.yml中添加了<code>show-sql: true</code>属性，所以说console会打印出SQL语句：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1569743944609.png" alt="控制台SQL语句"></p>
<h1 id="SpringBoot-注解"><a href="#SpringBoot-注解" class="headerlink" title="SpringBoot 注解"></a>SpringBoot 注解</h1><h2 id="hello请求"><a href="#hello请求" class="headerlink" title="/hello请求"></a>/hello请求</h2><ul>
<li><p>@<strong>SpringBootApplication</strong><br>标注一个<strong>主程序类</strong>，表明这是一个SpringBoot应用，程序开始入口</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@SpringBootApplication</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SpringBoot01HelloworldQuickApplication</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">SpringApplication</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">SpringBoot01HelloworldQuickApplication</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p>@<strong>ResponseBody</strong><br>表明这是一个响应<br>表示该方法的<strong>返回结果直接写入HTTP response body中</strong><br>一般在异步获取数据时使用，在使用@RequestMapping后，返回值通常解析为跳转路径，加上@responsebody后返回结果不会被解析为跳转路径，而是直接写入HTTP response body中。比如异步获取json数据，加上@responsebody后，会直接返回json数据。</p>
</li>
<li><p><strong>@RequestMapping(“/hello”)</strong><br><strong>响应</strong>/hello<strong>请求</strong></p>
</li>
<li><p><strong>@Controller</strong></p>
<p>是个Spring、SpringMVC的注解，<a target="_blank" rel="noopener" href="https://blog.csdn.net/fansili/article/details/78740877">@Controller 控制层，@Service 服务层，@Repository 持久层</a>；<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_41357573/article/details/84454502">或者这里</a></p>
</li>
<li><p><em><strong>@RestController:</strong></em><br>用于标注控制层组件(如struts中的action)，包含**@Controlle<strong>r和</strong>@ResponseBody**。</p>
</li>
</ul>
 <pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/*@ResponseBody
* @Controller
* 这两个注解可以合并成下面一个*/</span>
<span class="token annotation punctuation">@RestController</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">HelloController</span> <span class="token punctuation">&#123;</span>

    <span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">hello</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token string">"Hello Quick Spring Boot!!!"</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h2 id="配置文件-使用properties或yml注入Bean"><a href="#配置文件-使用properties或yml注入Bean" class="headerlink" title="配置文件,使用properties或yml注入Bean"></a>配置文件,使用properties或yml注入Bean</h2><ul>
<li><p><strong>@Component</strong><br>泛指组件，当组件不好归类的时候，我们可以使用这个注解进行标注。<br>@Component和@Bean都是用来<strong>注册Bean并装配到Spring容器</strong>中，但是Bean比Component的自定义性更强。可以实现一些Component实现不了的自定义加载类。</p>
</li>
<li><p><strong>@PropertySource(value = {“classpath:person.properties”})</strong><br>从指定的路径中导入配置文件（不指定这个注解的话，会自动从默认的全局配置文件application.properties中导入）</p>
</li>
<li><p><strong>@ConfigurationProperties(prefix = “person”)</strong><br>将配置文件（比如application.properties）中的person属性的值与当前类的<strong>属性绑定</strong></p>
</li>
<li><p><strong>@Value(“${person.last-name}”)</strong><br>将这个值绑定到标注下面的属性上</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Component</span>
<span class="token annotation punctuation">@PropertySource</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token string">"classpath:person.properties"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@ConfigurationProperties</span><span class="token punctuation">(</span>prefix <span class="token operator">=</span> <span class="token string">"person"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Person</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//Value赋值，一个一个的</span>
    <span class="token comment">// $ 取资源文件中的值</span>
    <span class="token comment">//@Value("$&#123;person.last-name&#125;")</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> lastName<span class="token punctuation">;</span>
    <span class="token comment">// # 计算表达式</span>
    <span class="token comment">//@Value("#&#123;11*2&#125;")</span>
    <span class="token keyword">private</span> <span class="token class-name">Integer</span> age<span class="token punctuation">;</span>
    <span class="token comment">//直接赋值</span>
    <span class="token comment">//@Value("true")</span>
    <span class="token keyword">private</span> <span class="token class-name">Boolean</span> boss<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Date</span> birth<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span><span class="token class-name">Object</span><span class="token punctuation">></span></span> maps<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Object</span><span class="token punctuation">></span></span> list<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token class-name">Dog</span> dog<span class="token punctuation">;</span>
   
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ul>
<hr>
<ul>
<li><strong>@ConfigurationProperties和@Value的比较</strong></li>
</ul>
<blockquote>
<ol>
<li>一般@Value导入时，是一个值一个值的导入，而@ConfigurationProperties是一批导入。</li>
<li>@Value支持SPEL，而@ConfigurationProperties比如</li>
</ol>
<ul>
<li>@Value(${person.last-name})：绑定person.last-name到当前属性</li>
<li>@Value(#{11*2})：计算11*2，就是22</li>
<li>@Value(“true”)：直接赋值为 true</li>
</ul>
<ol start="3">
<li><p>@Value不支持松散语法。</p>
<ul>
<li>在松散语法中，last-name与lastName是一样的，-n就是大写的N，而不支持松散语法的话就不一样</li>
</ul>
</li>
<li><p>@Value不支持JSR303数据校验</p>
<ul>
<li>就是说下面的这个@Email，会校验绑定的这个属性是否符合格式</li>
<li>加上@Email之前，需要一个这个@Validated注解</li>
<li>@Email：校验数据是否邮箱格式</li>
<li>如果校验不通过的话会抛IllegalStateException异常，数据不能绑定</li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Mynewclass/article/details/79086372">@Validated的详细使用</a></li>
</ul>
</li>
<li><p>@Value不支持复杂类型封装</p>
</li>
</ol>
</blockquote>
<hr>
<h2 id="配置类"><a href="#配置类" class="headerlink" title="配置类"></a>配置类</h2><ul>
<li><p><strong>@ImportResource（locations = {“classpath:beans.xml”}）</strong></p>
<p>标注在一个配置类上</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@ImportResource</span><span class="token punctuation">(</span>locations <span class="token operator">=</span> <span class="token string">"classpath:bean.xml"</span><span class="token punctuation">)</span>
<span class="token annotation punctuation">@SpringBootApplication</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SpringBoot01HelloworldQuickApplication</span> <span class="token punctuation">&#123;</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">SpringApplication</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">SpringBoot01HelloworldQuickApplication</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>导入spring的配置文件，bean.xml</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token prolog">&lt;?xml version="1.0" encoding="UTF-8"?></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>beans</span> <span class="token attr-name">xmlns</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>http://www.springframework.org/schema/beans<span class="token punctuation">"</span></span>
       <span class="token attr-name"><span class="token namespace">xmlns:</span>xsi</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>http://www.w3.org/2001/XMLSchema-instance<span class="token punctuation">"</span></span>
       <span class="token attr-name"><span class="token namespace">xsi:</span>schemaLocation</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>helloService<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.song.springboot.service.HelloService<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>beans</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这个xml的作用就是给HelloService类中注入一个id为helloService的Bean，可以在test中用以下来验证：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Autowired</span>
<span class="token class-name">ApplicationContext</span> ioc<span class="token punctuation">;</span>
  
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testHelloService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
    <span class="token keyword">boolean</span> b <span class="token operator">=</span> ioc<span class="token punctuation">.</span><span class="token function">containsBean</span><span class="token punctuation">(</span><span class="token string">"helloService"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
<li><p><strong>@Autowired</strong></p>
<p>自动注入。可以对成员变量、方法和构造函数进行标注。<code>@Autowired</code>注解的意思就是，当Spring发现<code>@Autowired</code>注解时，将自动在代码上下文中找到与其匹配（默认是类型匹配）的Bean，并自动注入到相应的地方去。</p>
</li>
<li><p><strong>@Confgiuration</strong></p>
<p>指出该类是 Bean 配置的信息源，相当于XML中的<beans></beans>，一般加在主类上。说明这个是个配置类。</p>
</li>
<li><p><strong>@Bean</strong></p>
<p>相当于XML中的<bean></bean>,<strong>放在方法的上面，而不是类</strong>，意思是产生一个bean,并交给spring管理。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//说明这是个配置类，返回一个HelloService对象注入到容器中，最后ioc容器中会含有一个helloService</span>
<span class="token annotation punctuation">@Configuration</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyAppConfig</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">HelloService</span> <span class="token function">helloService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">HelloService</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ul>
<h1 id="遇到的一些问题解决"><a href="#遇到的一些问题解决" class="headerlink" title="遇到的一些问题解决"></a>遇到的一些问题解决</h1><h2 id="添加schema-all-sql到resources中，不会自动建表"><a href="#添加schema-all-sql到resources中，不会自动建表" class="headerlink" title="添加schema-all.sql到resources中，不会自动建表"></a>添加schema-all.sql到resources中，不会自动建表</h2><h3 id="错误："><a href="#错误：" class="headerlink" title="错误："></a>错误：</h3><p>​    添加schema-all.sql到resources中，不会自动建表</p>
<h3 id="解决："><a href="#解决：" class="headerlink" title="解决："></a>解决：</h3><p>​    在application.properties配置文件中添加：</p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token comment">##   加这个，不然不会执行schema-all或者下面自定义sql脚本</span>
<span class="token attr-name">spring.datasource.initialization-mode</span><span class="token punctuation">=</span><span class="token attr-value">always</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>同时，如果加schema自定义sql位置，也是需要加是这个always属性的</p>
<pre class="line-numbers language-properties" data-language="properties"><code class="language-properties"><span class="token comment">##   设置默认的sql位置</span>
<span class="token attr-name">spring.datasource.schema</span><span class="token punctuation">=</span><span class="token attr-value">classpath:department.sql</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<h2 id="修改Durid，新建config配置绑定属性："><a href="#修改Durid，新建config配置绑定属性：" class="headerlink" title="修改Durid，新建config配置绑定属性："></a>修改Durid，新建config配置绑定属性：</h2><h3 id="报错："><a href="#报错：" class="headerlink" title="报错："></a>报错：</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">Failed</span> <span class="token keyword">to</span> <span class="token namespace">bind</span> properties under <span class="token string">'spring.datasource'</span> <span class="token keyword">to</span> <span class="token namespace">javax<span class="token punctuation">.</span>sql<span class="token punctuation">.</span></span><span class="token class-name">DataSource</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h3 id="原因："><a href="#原因：" class="headerlink" title="原因："></a>原因：</h3><p>在yml配置文件中，设置的属性：</p>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">##   配置监控统计拦截的filters，去掉后监控界面sql无法统计，&#39;wall&#39;用于防火墙
 filters: stat,wall,log4j
 maxPoolPreparedStatementPerConnectionSize: 20
 useGlobalDataSourceStat: true
 connectionProperties: druid.stat.mergeSql&#x3D;true;druid.stat.slowSqlMillis&#x3D;500
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>其中filters引用了log4j，但是pom.xml中没有，所以说报错</p>
<h3 id="解决：-1"><a href="#解决：-1" class="headerlink" title="解决："></a>解决：</h3><p>在pom.xml中添加log4j的依赖：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">></span></span>log4j<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">></span></span>log4j<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">></span></span>1.2.12<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<h2 id="SpingBoot-Druid，404错误"><a href="#SpingBoot-Druid，404错误" class="headerlink" title="SpingBoot+Druid，404错误"></a>SpingBoot+Druid，404错误</h2><h3 id="错误：-1"><a href="#错误：-1" class="headerlink" title="错误："></a>错误：</h3><p>网页404：</p>
<blockquote>
<h2 id="Whitelabel-Error-Page"><a href="#Whitelabel-Error-Page" class="headerlink" title="Whitelabel Error Page"></a>Whitelabel Error Page</h2><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>
<p>Sat Sep 28 09:21:10 CST 2019</p>
<p>There was an unexpected error (type=Not Found, status=404).</p>
<p>No message available</p>
</blockquote>
<h3 id="原因：-1"><a href="#原因：-1" class="headerlink" title="原因："></a>原因：</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java">  <span class="token comment">//1.配置一个管理后后台的servlet,这个Bean加到容器中</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">ServletRegistrationBean</span> <span class="token function">statViewServlet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token class-name">ServletRegistrationBean</span> bean <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ServletRegistrationBean</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StatViewServlet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"/druid/"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


        <span class="token comment">//配置初始化参数，因为下面需要传入一个map</span>
        <span class="token class-name">Map</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">,</span> <span class="token class-name">String</span><span class="token punctuation">></span></span> initParams <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HashMap</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">//这个东西的参数去StatViewServlet类里面，他的父类ResourceServlet里面找</span>
        initParams<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"loginUsername"</span><span class="token punctuation">,</span> <span class="token string">"admin"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        initParams<span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span><span class="token string">"loginPassword"</span><span class="token punctuation">,</span> <span class="token string">"123456"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">//        initParams.put("allow", "");    //允许谁访问，默认是所有</span>
<span class="token comment">//        initParams.put("deny","192.168.15.21"); //拒绝谁放问，这里是假设的IP地址</span>
        <span class="token comment">//需要传入一个map</span>
        bean<span class="token punctuation">.</span><span class="token function">setInitParameters</span><span class="token punctuation">(</span>initParams<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> bean<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>其中的<code>ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), &quot;/druid/&quot;);</code>，第二个参数，urlMappings写错了。应该是<code>&quot;/druid/*&quot;</code>，是druid 路径下所有映射。</p>
<h3 id="修改："><a href="#修改：" class="headerlink" title="修改："></a>修改：</h3><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token class-name">ServletRegistrationBean</span> bean <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ServletRegistrationBean</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">StatViewServlet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"/druid/*"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>即可。</p>
<h2 id="整合JPA，报错Caused-by-org-hibernate-AnnotationException-No-identifier-specified-for-entity"><a href="#整合JPA，报错Caused-by-org-hibernate-AnnotationException-No-identifier-specified-for-entity" class="headerlink" title="整合JPA，报错Caused by: org.hibernate.AnnotationException: No identifier specified for entity:"></a>整合JPA，报错Caused by: org.hibernate.AnnotationException: No identifier specified for entity:</h2><h3 id="错误：-2"><a href="#错误：-2" class="headerlink" title="错误："></a>错误：</h3><blockquote>
<p>这个前面还有个错误，好像是什么不能注入容器，根据console提示修改一下yml就行啦，加上：</p>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">spring: 
  main:
    allow-bean-definition-overriding: true<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>大概是在容器中把我们写的UserRepository注入进去覆盖原来自有的？</p>
</blockquote>
<p>启动SpringBoot时报错：</p>
<pre class="line-numbers language-none"><code class="language-none">org.springframework.beans.factory.BeanCreationException: Error creating bean with name &#39;entityManagerFactory&#39; defined in class path resource [org&#x2F;springframework&#x2F;boot&#x2F;autoconfigure&#x2F;orm&#x2F;jpa&#x2F;HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.song.springboot.entity.User


Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.song.springboot.entity.User<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="原因：-2"><a href="#原因：-2" class="headerlink" title="原因："></a>原因：</h3><p>百度了半天，都在说是实体类的注解写错了，需要加上主键的@Id，我对了半天也没发现错误。最终发现：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">import</span> <span class="token namespace">org<span class="token punctuation">.</span>springframework<span class="token punctuation">.</span>data<span class="token punctuation">.</span>annotation<span class="token punctuation">.</span></span><span class="token class-name">Id</span><span class="token punctuation">;</span>

<span class="token keyword">import</span> <span class="token namespace">javax<span class="token punctuation">.</span>persistence<span class="token punctuation">.</span></span><span class="token operator">*</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>还真是@Id的问题，因为我加@Id的时候导包导入错了，不是springframework的@Id注解而是persistence里面的。</p>
<h3 id="解决：-2"><a href="#解决：-2" class="headerlink" title="解决："></a>解决：</h3><p>删掉上面那个id的import就行。</p>
<h2 id="JPA查询报错"><a href="#JPA查询报错" class="headerlink" title="JPA查询报错"></a>JPA查询报错</h2><h3 id="错误：-3"><a href="#错误：-3" class="headerlink" title="错误："></a>错误：</h3><p>Controller中查找方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//查找用户</span>
  <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/user/jpa/select/&#123;id&#125;"</span><span class="token punctuation">)</span>
  <span class="token keyword">public</span> <span class="token class-name">User</span> <span class="token function">getUser</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"id"</span><span class="token punctuation">)</span> <span class="token class-name">Integer</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token class-name">User</span> user <span class="token operator">=</span> userRepository<span class="token punctuation">.</span><span class="token function">getOne</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> user<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>访问这个url然后报错：</p>
<blockquote>
<p>Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: <strong>No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor</strong> and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.song.springboot.entity.User$HibernateProxy$j7VI3Nk2[&quot;hibernateLazyInitializer&quot;])</p>
</blockquote>
<h3 id="原因：-3"><a href="#原因：-3" class="headerlink" title="原因："></a>原因：</h3><p>​    因为返回值是个实体类对象的原因。</p>
<p>​    hibernate会给每个被管理的对象加上hibernateLazyInitializer属性，同时struts-jsonplugin或者其他的jsonplugin都是如此。</p>
<p>​    因为jsonplugin用的是java的内审机制，hibernate会给被管理的pojo加入一个hibernateLazyInitializer属性。jsonplugin通过java的反射机制将pojo转换成json，会把hibernateLazyInitializer也拿出来操作。但是hibernateLazyInitializer无法由反射得到，也就是说从对象中无法获取，所以就抛异常了。 </p>
<h3 id="解决：-3"><a href="#解决：-3" class="headerlink" title="解决："></a>解决：</h3><p>在User实体类中加入如下注解：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//使用JPA注解配置映射关系</span>
<span class="token annotation punctuation">@Entity</span>     <span class="token comment">//告诉JPA这是个实体类</span>
<span class="token annotation punctuation">@Table</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"tbl_user"</span><span class="token punctuation">)</span>   <span class="token comment">//告诉这个类和数据库中的哪个表相对应，不写的话就是默认的小写类名user</span>
<span class="token annotation punctuation">@JsonIgnoreProperties</span><span class="token punctuation">(</span>value<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token string">"hibernateLazyInitializer"</span><span class="token punctuation">,</span><span class="token string">"handler"</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">User</span> <span class="token punctuation">&#123;</span>
    <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>在类上声明的@JsonIgnoreProperties，是忽略Hibernate的延迟加载的一些属性”hibernateLazyInitializer”, “handler”, “fieldHandler”，这些属性在实体类里没有所以要忽略掉，否则会报错。</p>
<h2 id="Java反射来输出对象的所有属性"><a href="#Java反射来输出对象的所有属性" class="headerlink" title="Java反射来输出对象的所有属性"></a>Java反射来输出对象的所有属性</h2><pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">testReflect</span><span class="token punctuation">(</span><span class="token class-name">Object</span> model<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">Field</span><span class="token punctuation">[</span><span class="token punctuation">]</span> field <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getDeclaredFields</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment">//获取实体类的所有属性，返回Field数组</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> field<span class="token punctuation">.</span>length<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>     <span class="token comment">//遍历所有属性</span>
        <span class="token class-name">String</span> name <span class="token operator">=</span> field<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment">//获取属性的名字</span>

        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute name:"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
        name <span class="token operator">=</span> name<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toUpperCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> name<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//将属性的首字符大写，方便构造get，set方法</span>
        <span class="token class-name">String</span> type <span class="token operator">=</span> field<span class="token punctuation">[</span>j<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">getGenericType</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment">//获取属性的类型</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.lang.String"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>   <span class="token comment">//如果type是类类型，则前面包含"class "，后面跟类名</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">String</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment">//调用getter方法获取属性值</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.lang.Integer"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Integer</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Integer</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.lang.Short"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Short</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Short</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.lang.Double"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Double</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Double</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.lang.Boolean"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Boolean</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Boolean</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>type<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span><span class="token string">"class java.util.Date"</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token class-name">Method</span> m <span class="token operator">=</span> model<span class="token punctuation">.</span><span class="token function">getClass</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getMethod</span><span class="token punctuation">(</span><span class="token string">"get"</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">Date</span> value <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token class-name">Date</span><span class="token punctuation">)</span> m<span class="token punctuation">.</span><span class="token function">invoke</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>value <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"attribute value:"</span> <span class="token operator">+</span> value<span class="token punctuation">.</span><span class="token function">toLocaleString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="使用sql将一个表的数据导入另一个表："><a href="#使用sql将一个表的数据导入另一个表：" class="headerlink" title="使用sql将一个表的数据导入另一个表："></a>使用sql将一个表的数据导入另一个表：</h3><pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">insert</span> <span class="token keyword">into</span> jc_rw<span class="token punctuation">(</span>guid<span class="token punctuation">,</span>rwid<span class="token punctuation">,</span>xmbh<span class="token punctuation">,</span>xmmc<span class="token punctuation">,</span>xfsj<span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token keyword">select</span> rwid<span class="token punctuation">,</span>rwid<span class="token punctuation">,</span>xmbh<span class="token punctuation">,</span>xmmc<span class="token punctuation">,</span>xfsj <span class="token keyword">from</span> jc_db_task<span class="token punctuation">)</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>设置一个表中的某一列全部为这个数据：</p>
<pre class="line-numbers language-sql" data-language="sql"><code class="language-sql"><span class="token keyword">update</span> jc_rw <span class="token keyword">set</span> cdrwks<span class="token operator">=</span><span class="token string">'监测科'</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h2 id="整合Mybatis-Plus和Lombok"><a href="#整合Mybatis-Plus和Lombok" class="headerlink" title="整合Mybatis-Plus和Lombok"></a>整合Mybatis-Plus和Lombok</h2><p>主要是mybaits-plus</p>
<ol>
<li><p>修改pom文件，添加依赖</p>
</li>
<li><p>修改yml配置文件，将mybatis的配置删除，增加mybatis-plus配置</p>
<pre class="line-numbers language-yml" data-language="yml"><code class="language-yml">## MyBatis配置
## https:&#x2F;&#x2F;baomidou.com&#x2F;config&#x2F;
mybatis-plus:
  ## 对应的 XML 文件位置
  mapperLocations: classpath*:mapper&#x2F;**&#x2F;*Mapper.xml
  ## 实体扫描，多个package用逗号或者分号分隔
  typeAliasesPackage: com.ruoyi.**.domain
  ## 针对 typeAliasesPackage，如果配置了该属性，则仅仅会扫描路径下以该类作为父类的域对象
  #typeAliasesSuperType: Class&lt;?&gt;
  ## 如果配置了该属性，SqlSessionFactoryBean 会把该包下面的类注册为对应的 TypeHandler
  #typeHandlersPackage: null
  ## 如果配置了该属性，会将路径下的枚举类进行注入，让实体类字段能够简单快捷的使用枚举属性
  #typeEnumsPackage: null
  ## 启动时是否检查 MyBatis XML 文件的存在，默认不检查
  checkConfigLocation: false
  ## 通过该属性可指定 MyBatis 的执行器，MyBatis 的执行器总共有三种：
  ## SIMPLE：该执行器类型不做特殊的事情，为每个语句的执行创建一个新的预处理语句（PreparedStatement）
  ## REUSE：该执行器类型会复用预处理语句（PreparedStatement）
  ## BATCH：该执行器类型会批量执行所有的更新语句
  executorType: SIMPLE
  ## 指定外部化 MyBatis Properties 配置，通过该配置可以抽离配置，实现不同环境的配置部署
  configurationProperties: null
  configuration:
    ## 自动驼峰命名规则（camel case）映射
    ## 如果您的数据库命名符合规则无需使用 @TableField 注解指定数据库字段名
    mapUnderscoreToCamelCase: true
    ## 默认枚举处理类,如果配置了该属性,枚举将统一使用指定处理器进行处理
    ## org.apache.ibatis.type.EnumTypeHandler : 存储枚举的名称
    ## org.apache.ibatis.type.EnumOrdinalTypeHandler : 存储枚举的索引
    ## com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler : 枚举类需要实现IEnum接口或字段标记@EnumValue注解.
    defaultEnumTypeHandler: org.apache.ibatis.type.EnumTypeHandler
    ## 当设置为 true 的时候，懒加载的对象可能被任何懒属性全部加载，否则，每个属性都按需加载。需要和 lazyLoadingEnabled 一起使用。
    aggressiveLazyLoading: true
    ## MyBatis 自动映射策略
    ## NONE：不启用自动映射
    ## PARTIAL：只对非嵌套的 resultMap 进行自动映射
    ## FULL：对所有的 resultMap 都进行自动映射
    autoMappingBehavior: PARTIAL
    ## MyBatis 自动映射时未知列或未知属性处理策
    ## NONE：不做任何处理 (默认值)
    ## WARNING：以日志的形式打印相关警告信息
    ## FAILING：当作映射失败处理，并抛出异常和详细信息
    autoMappingUnknownColumnBehavior: NONE
    ## Mybatis一级缓存，默认为 SESSION
    ## SESSION session级别缓存，同一个session相同查询语句不会再次查询数据库
    ## STATEMENT 关闭一级缓存
    localCacheScope: SESSION
    ## 开启Mybatis二级缓存，默认为 true
    cacheEnabled: true
  global-config:
    ## 是否打印 Logo banner
    banner: true
    ## 是否初始化 SqlRunner
    enableSqlRunner: false
    dbConfig:
      ## 主键类型
      ## AUTO 数据库ID自增
      ## NONE 空
      ## INPUT 用户输入ID
      ## ASSIGN_ID 全局唯一ID
      ## ASSIGN_UUID 全局唯一ID UUID
      idType: AUTO
      ## 表名前缀
      tablePrefix: null
      ## 字段 format,例: %s,(对主键无效)
      columnFormat: null
      ## 表名是否使用驼峰转下划线命名,只对表名生效
      tableUnderline: true
      ## 大写命名,对表名和字段名均生效
      capitalMode: false
      ## 全局的entity的逻辑删除字段属性名
      logicDeleteField: null
      ## 逻辑已删除值
      logicDeleteValue: 1
      ## 逻辑未删除值
      logicNotDeleteValue: 0
      ## 字段验证策略之 insert,在 insert 的时候的字段验证策略
      ## IGNORED 忽略判断
      ## NOT_NULL 非NULL判断
      ## NOT_EMPTY 非空判断(只对字符串类型字段,其他类型字段依然为非NULL判断)
      ## DEFAULT 默认的,一般只用于注解里
      ## NEVER 不加入 SQL
      insertStrategy: NOT_NULL
      ## 字段验证策略之 update,在 update 的时候的字段验证策略
      updateStrategy: NOT_NULL
      ## 字段验证策略之 select,在 select 的时候的字段验证策略既 wrapper 根据内部 entity 生成的 where 条件
      selectStrategy: NOT_NULL
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre></li>
</ol>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">SongX64</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://songx86.gitee.io/article/907c87e0.html">https://songx86.gitee.io/article/907c87e0.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">SongX64</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                                <a href="/tags/Springboot/">
                                    <span class="chip bg-color">Springboot</span>
                                </a>
                            
                                <a href="/tags/%E5%B8%B8%E7%94%A8%E7%BB%84%E4%BB%B6/">
                                    <span class="chip bg-color">常用组件</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'gRuzkj3uDnUjERvWlFkWkYjF-gzGzoHsz',
        appKey: 'tCCMKQDflcsl0hOAh2CUfvPP',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/article/27261f5e.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1/06.jpg" class="responsive-img" alt="GMIS2017大会演讲笔记——朱军详解珠算：贝叶斯深度学习的GPU库">
                        
                        <span class="card-title">GMIS2017大会演讲笔记——朱军详解珠算：贝叶斯深度学习的GPU库</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            清华大学朱军详解珠算：贝叶斯深度学习的GPU库
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%A7%91%E7%A0%94/" class="post-category">
                                    科研
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%A7%91%E7%A0%94/">
                        <span class="chip bg-color">科研</span>
                    </a>
                    
                    <a href="/tags/%E7%8F%A0%E7%AE%97/">
                        <span class="chip bg-color">珠算</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/article/d7c4fee9.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1/02.jpg" class="responsive-img" alt="简单了解清华大学朱军珠算框架">
                        
                        <span class="card-title">简单了解清华大学朱军珠算框架</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            清华大学朱军，研发的珠算：贝叶斯深度学习的GPU库，简单了解其概念
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-02-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%A7%91%E7%A0%94/" class="post-category">
                                    科研
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%A7%91%E7%A0%94/">
                        <span class="chip bg-color">科研</span>
                    </a>
                    
                    <a href="/tags/%E7%8F%A0%E7%AE%97/">
                        <span class="chip bg-color">珠算</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="767683882"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">SongX64</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
			<br>
				<a href="https://beian.miit.gov.cn/" target="_blank">鲁ICP备2021015839号-1</a>
				 | 
				<img src="/medias/icp.png" style="vertical-align: text-bottom;" />
		 		<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=37083102000087">鲁公网安备 37083102000087号</a>
            </span>
			
		 
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/SongX64" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:song.x64@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=song-x64@qq.com" class="tooltipped" target="_blank" data-tooltip="QQ联系我: song-x64@qq.com" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/330452"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.5'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>

</html>
